package com.kpx.app.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kpx.app.BuildConfig;
import com.kpx.app.bean.Page;
import com.kpx.app.utils.datautils.LogUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者： Ryan
 * 描述： 请求结果转换为JSON对象
 * 创建时间：2015/3/23 14:14.
 */
public class NetworkResult {
    private static final String TAG = "NetworkResult";
    private int code = -1;
    private String msg;
    private String data;
    private Page page;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public <T> T getObject(Class<T> c) {
        try {
            return JSON.parseObject(data, c);
        } catch (Exception e) {
            LogUtils.e(TAG, " ");
            return null;
        }

    }

    public <T> T getObject(String data, Class<T> c) {
        try {
            return JSON.parseObject(data, c);
        } catch (Exception e) {
            LogUtils.e(TAG, " ");
            return null;
        }
    }

    public <T> List<T> getObjectList(Class<T> c) {
        LogUtils.i("TAG", " =========  " + data);
        try {
            return JSON.parseArray(data, c);
        } catch (Exception e) {
            return new ArrayList<T>();
        }
    }

    public <T> List<T> getObjectList(String data, Class<T> c) {
        List<T> objectList = null;
        try {
            objectList = JSON.parseArray(data, c);
        } catch (Exception e) {

        }
        return objectList == null ? new ArrayList<T>() : objectList;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Page getPage() {
        return page;
    }

    public void setPage(Page page) {
        this.page = page;
    }

    public String getObjectString(String key) {
        try {
            JSONObject jsonObject = JSON.parseObject(data);
            if (jsonObject == null || !jsonObject.containsKey(key)) {
                return "";
            }
            return jsonObject.getString(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getObjectString(String data, String key) {
        JSONObject jsonObject = JSON.parseObject(data);
        if (jsonObject == null || !jsonObject.containsKey(key)) {
            return "";
        }
        return jsonObject.getString(key);
    }

    @Override
    public String toString() {
        if (!BuildConfig.DEBUG) {
            return super.toString();
        }
        return "NetworkResult{" +
                "code=" + code +
                ", data='" + data + '\'' +
                ", page=" + page +
                '}';
    }
}
